#include "SDL/SDL.h"
#include "SDL/SDL_draw.h"
#include "SDL/SDL_ttf.h"
#include "SDL_Button.h"
#include "util.h"

/*  创建按钮方法，结果返回该按钮的指针
    x:按钮左上角的x坐标
    y:按钮左上角的y坐标
    w:按钮宽度
    h:按钮高度
    text:按钮文本内容 
    font:按钮字体
*/
Button SDL_Button(int x, int y, int w, int h, char *text, TTF_Font *font)
{
    Button button;
    button.box.x = x;
    button.box.y = y;
    button.box.w = w;
    button.box.h = h;
    button.text = text;
    SDL_Color textColor = {0, 0, 0};
    button.message = TTF_RenderUTF8_Solid(font, text, textColor);
    return button;
}

/*  按钮事件处理
    button:要绑定事件的按钮指针
    e:事件
    on_mouse_click():回调函数
*/
void handle_button_events(Button *button, SDL_Event e, void (*on_mouse_click)(Button *))
{
    int x = 0, y = 0;
    if (e.type == SDL_MOUSEBUTTONDOWN)
    {
        if (e.button.button == SDL_BUTTON_LEFT)
        {
            x = e.button.x;
            y = e.button.y;
            if ((x > button->box.x) && (x < button->box.x + button->box.w) && (y > button->box.y) && (y < button->box.y + button->box.h))
            {
                on_mouse_click(button);
            }
        }
    }
}

/*  显示按钮
    button:按钮指针
    screen:要显示的屏幕
*/
void set_button_to_screen(Button *button, SDL_Surface *screen)
{
    Draw_FillRound(screen, button->box.x, button->box.y, button->box.w, button->box.h, 5, SDL_MapRGB(screen->format, 0xff, 0xff, 0xff));
    apply_surface((button->box.w - button->message->w) / 2.0 + button->box.x, (button->box.h - button->message->h) / 2.0 + button->box.y, button->message, screen);
}

/*  释放按钮
    button:按钮指针
 */
void clean_Button(Button *button)
{
    SDL_FreeSurface(button->message);
}